package ocean.chinacraft.common.event.world;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import ocean.chinacraft.common.ModBlocks;
import ocean.chinacraft.common.constants.Constants;

import java.util.List;

/**
 * 世界监听
 *
 * @author zhang
 * @since 2022/1/7
 */
@Mod.EventBusSubscriber(modid = Constants.MOD_ID)
public class ModWorldEvent {

    private static final ResourceLocation RESOURCE = new ResourceLocation("bamboo_jungle");

    @SubscribeEvent
    public static void worldEvent(final TickEvent.WorldTickEvent event) {
        World world = event.world;
        if (world.isThundering() && world instanceof ServerWorld) {
            ServerWorld serverWorld = (ServerWorld) world;
            serverWorld.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getOptional(RESOURCE).ifPresent(res -> {
                List<? extends PlayerEntity> players = world.players();
                for (PlayerEntity player : players) {
                    if (player.isAlive()) {
                        BlockPos biomePos = serverWorld.findNearestBiome(res, player.blockPosition(), 6400, 8);
                        if (biomePos != null) {
                            world.setBlock(biomePos, ModBlocks.LIGHTNING_BAMBOO_SAPLING.get().defaultBlockState(), 3);
                        }
                    }
                }
            });
        }
    }
}
